﻿using Microsoft.AspNetCore.Mvc;
using System.Text;
using WkHtmlToPdfDotNet;
using WkHtmlToPdfDotNet.Contracts;
using Zero.WebAPI.Framework.Config.Helper;
using Zero.WebAPI.Framework.Helper;

namespace Zero.WebAPI.Framework.Helper
{
    public class PDFHelper
    {
        private static IConverter converter;

        static PDFHelper()
        {
            converter = IOCHelper.GetService<IConverter>();
        }

        public static byte[] HtmlToPDF([FromForm] string htmlData, bool base64Str = true)
        {
            string Content = string.Empty;
            if (base64Str)
            {
                byte[] body = Convert.FromBase64String(htmlData);
                Content = Encoding.UTF8.GetString(body);
            }
            else
            {
                Content = htmlData;
            }

            GlobalSettings globalSettings = GetGlobalSetting();
            ObjectSettings objectSettings = GetObjectSettings();
            objectSettings.HtmlContent = Content;

            HtmlToPdfDocument doc = new HtmlToPdfDocument()
            {
                GlobalSettings = globalSettings,
                Objects =
                {
                    objectSettings
                }
            };
            try
            {
                byte[] buff = converter.Convert(doc);
                return buff;
            }
            catch
            {
                throw;
            }
        }

        private static GlobalSettings GetGlobalSetting()
        {
            GlobalSettings globalSettings = new GlobalSettings();
            #region margin解析

            string marginStr = ConfigHelper.Get<string>("PDFConfig", "GlobalSettings", "Margin");
            double[] margin = new double[4];
            string[] marginVals = marginStr.Split(',');
            if (marginVals.Length == 1)
            {
                if (!double.TryParse(marginVals[0], out double d))
                {
                    throw new Exception("margin 解析错误，请检查设置的值是否正确");
                }
                margin[0] = d;
                margin[1] = d;
                margin[2] = d;
                margin[3] = d;
            }
            else if (marginVals.Length == 2)
            {
                if (!(double.TryParse(marginVals[0], out double d1) && double.TryParse(marginVals[1], out double d2)))
                {
                    throw new Exception("margin 解析错误，请检查设置的值是否正确");
                }
                margin[0] = d1;
                margin[1] = d2;
                margin[2] = d1;
                margin[3] = d2;
            }
            else if (marginVals.Length == 3)
            {
                if (!(double.TryParse(marginVals[0], out double d1) && double.TryParse(marginVals[1], out double d2) && double.TryParse(marginVals[2], out double d3)))
                {
                    throw new Exception("margin 解析错误，请检查设置的值是否正确");
                }
                margin[0] = d1;
                margin[1] = d2;
                margin[2] = d2;
                margin[3] = d3;
            }
            else
            {
                if (!(double.TryParse(marginVals[0], out double d1)
                    && double.TryParse(marginVals[1], out double d2)
                    && double.TryParse(marginVals[2], out double d3)
                    && double.TryParse(marginVals[3], out double d4)
                    ))
                {
                    throw new Exception("margin 解析错误，请检查设置的值是否正确");
                }
                margin[0] = d1;
                margin[1] = d2;
                margin[2] = d3;
                margin[3] = d4;
            }
            globalSettings.Margins = new MarginSettings(margin[0], margin[1], margin[2], margin[3]);

            #endregion

            #region ColorMode 解析

            string colorModeStr = ConfigHelper.Get<string>("PDFConfig", "GlobalSettings", "ColorMode");
            if (!Enum.TryParse<ColorMode>(colorModeStr, out ColorMode colorMode))
                throw new Exception("ColorMode 解析错误，请检查设置的值是否正确");
            globalSettings.ColorMode = colorMode;

            #endregion

            #region 显示方向

            string orientationStr = ConfigHelper.Get<string>("PDFConfig", "GlobalSettings", "Orientation");
            if (!Enum.TryParse<Orientation>(orientationStr, out Orientation orientation))
                throw new Exception("Orientation 解析错误，请检查设置的值是否正确");
            globalSettings.Orientation = orientation;

            #endregion

            #region PaperKind

            string pageSizeStr = ConfigHelper.Get<string>("PDFConfig", "GlobalSettings", "PageSize");
            if (!Enum.TryParse<PaperKind>(pageSizeStr, out PaperKind paperKind))
                throw new Exception("PaperKind 解析错误，请检查设置的值是否正确");
            globalSettings.PaperSize = paperKind;

            #endregion

            return globalSettings;
        }

        private static ObjectSettings GetObjectSettings()
        {
            ObjectSettings objectSettings = new ObjectSettings();
            bool pageCount = ConfigHelper.Get<bool>("PDFConfig", "ObjectSettings", "PageCount");
            string encoding = ConfigHelper.Get<string>("PDFConfig", "ObjectSettings", "Encoding");
            objectSettings.PagesCount = pageCount;
            objectSettings.WebSettings = new WebSettings() { DefaultEncoding = encoding };

            HeaderSettings headerSettings = new HeaderSettings();
            headerSettings.FontSize = ConfigHelper.Get<int>("PDFConfig", "ObjectSettings", "HeaderSettings", "FontSize");
            headerSettings.FontName = ConfigHelper.Get<string>("PDFConfig", "ObjectSettings","HeaderSettings", "FontName");
            headerSettings.Left = ConfigHelper.Get<string>("PDFConfig", "ObjectSettings","HeaderSettings", "Left") ?? "";
            headerSettings.Center = ConfigHelper.Get<string>("PDFConfig", "ObjectSettings","HeaderSettings", "Center") ?? "";
            headerSettings.Right = ConfigHelper.Get<string>("PDFConfig", "ObjectSettings","HeaderSettings", "Right") ?? "";
            headerSettings.Line = ConfigHelper.Get<bool>("PDFConfig", "ObjectSettings","HeaderSettings", "Line");
            headerSettings.Spacing = ConfigHelper.Get<double>("PDFConfig", "ObjectSettings","HeaderSettings", "Spacing");
            objectSettings.HeaderSettings = headerSettings;

            return objectSettings;
        }
    }
}
